package com.neusoft.techan.controller;

import org.springframework.web.bind.annotation.*;

import com.neusoft.techan.model.Admin;
import com.neusoft.techan.service.AdminService;
import com.neusoft.techan.utils.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;  


@RestController
@RequestMapping("/admin")
public class AdminController {
    @Autowired
    private AdminService adminService;
    
    /**
     * 登录
     */
    @PostMapping("/login")
    public Result<Admin> login(Admin admin,HttpServletRequest request){
    	Admin ad=adminService.login(admin);
    	if(ad!=null){
    		 HttpSession session = request.getSession();
    		 session.setAttribute("admin", ad);
    		 return ResultGenerator.genSuccessResult(ad);
    	}else{
    		 Result<Admin> result = new Result<Admin>();
    	     result.setResultCode(Constants.RESULT_CODE_SERVER_ERROR);
    	     return result;
    	}
    }
    
    /**
     * 登出
     */
    @PostMapping("/logout")
    public Result<?> logout(Admin admin,HttpServletResponse response,HttpServletRequest request){
    	//清除session
    	HttpSession session = request.getSession();
    	session.removeAttribute("admin");
    	return null;
    }
    

    /**
     * 新增
     */
    @PostMapping("/insert")
    public Result<String> insert(@RequestBody Admin admin){
        int res=adminService.insert(admin);
        if(res==1){
            return ResultGenerator.genSuccessResult();
        }else{
        	return ResultGenerator.genFailResult(null);
        }
    }

    /**
     * 删除
     */
    @GetMapping("/delete/{ids}")
    public Result<String> delete(@PathVariable("ids") String ids){
    	if(null==ids||ids.equals("")){
    		return ResultGenerator.genFailResult(null);
    	}
        String str[]=ids.split(",");
        for(String s:str){
            adminService.deleteByPrimaryKey(Integer.valueOf(s));
        }
        return ResultGenerator.genSuccessResult();
    }
    
    /**
     * 更新
     */
    @PostMapping("/update")
    public Result<String> update(@RequestBody Admin admin){
    	int res=adminService.updateByPrimaryKey(admin);
    	if(res==1){
    		return ResultGenerator.genSuccessResult();
    	}else{
    		return ResultGenerator.genFailResult(null);
    	}
    }
  
}